
package com.kweative.model.relation;

import com.kweative.model.Index;
import com.kweative.model.Schema;
import com.kweative.model.Table;
import com.kweative.model.apt.annotation.TableDeclaration;
import com.kweative.model.data.Row;
import com.kweative.model.exception.StructureException;
import com.kweative.model.column.Column;
import com.kweative.model.column.ColumnInteger;

import com.kweative.model.query.WhereStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class RelationMany2Many<P extends Table,C extends Table> extends Relation<P,C> implements IMultiRelation<P,C> {
    RelationTable relationTable;
    public RelationMany2Many(P parent) {
        super(parent);
    }

    @Override
    protected void makeStructure() {
        String tableName = String.format("%s_%s_m2m",getParent().getName(),getChild().getName());
        relationTable = new RelationTable(tableName,getParent(),getChild());
        relationTable.setSchema(this.getParent().getSchema());

    }

    @Override
    public WhereStatement join(WhereStatement where) {
        where.join(relationTable).where(getParent().__primary).isEqual(relationTable.ParentKey);
        where.join(getChild()).where(getChild().__primary).isEqual(relationTable.ChildKey);
        where.orderBy(relationTable.Sorting,WhereStatement.Order.ASCENDING);
        return where;

    }

    public void add(Row<P> parent, Row<C> child) {
        try {
            relationTable.insert().set(relationTable.ParentKey,parent.__primary).set(relationTable.ChildKey,child.__primary).execute();
        } catch (SQLException ex) {
            Logger.getLogger(RelationMany2Many.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void remove(Row<P> parent, Row<C> child) {
        try {
            relationTable.delete().using(relationTable.IMain, parent.__primary, child.__primary).execute();
        } catch (SQLException ex) {
            Logger.getLogger(RelationMany2Many.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    
}
